package com.woniu.service.impl;


import com.woniu.outlet.dao.WorkerPoMapper;
import com.woniu.outlet.po.WorkerPo;
import com.woniu.outlet.po.WorkerPoExample;
import com.woniu.service.WorkerService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

@Service("workerService")
public class WorkerServiceImpl implements WorkerService {

    @Autowired
    private WorkerPoMapper workerPoMapper;
    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        WorkerPoExample workerExample = new WorkerPoExample();
        WorkerPoExample.Criteria criteria = workerExample.createCriteria();
        criteria.andAccountEqualTo(username);
        List<WorkerPo> workerList = workerPoMapper.selectByExample(workerExample);
        if (workerList == null || workerList.size() == 0) {
//            throw new UsernameNotFoundException("用户未找到");
            throw null;
        } else {
            List<String> percodes = workerPoMapper.getPercodeByUsername(username);
            List<GrantedAuthority> authorities = new ArrayList<>();
            percodes.forEach(percode -> {
                authorities.add(new SimpleGrantedAuthority(percode));
            });

            UserDetails userDetails =
                    new org.springframework.security.core.userdetails.User(workerList.get(0).getUsername(),
                            workerList.get(0).getPassword(), authorities);
            return userDetails;

        }
    }
}
